package com.huawei.rbac.service.impl;

import com.huawei.rbac.domain.Role;
import com.huawei.rbac.mapper.EmployeeMapper;
import com.huawei.rbac.mapper.RoleMapper;
import com.huawei.rbac.query.QueryObject;
import com.huawei.rbac.result.PageResult;
import com.huawei.rbac.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService{

    @Autowired
    private RoleMapper mapper;

    @Autowired
    private EmployeeMapper employeeMapper;

    public void saveOrUpdate(Role r, Long[] permissionIds) {
        if(r.getId() == null){
            mapper.insert(r);
        }else {
            mapper.updateByPrimaryKey(r);

            mapper.deleteRoleAndPermissionRelation(r.getId());
        }
        if(permissionIds != null){
            for (Long permissionId : permissionIds) {
                mapper.insertRoleAndPermissionRelation(r.getId(), permissionId);
            }
        }

    }

    public void delete(Long id) {
        mapper.deleteByPrimaryKey(id);

        mapper.deleteRoleAndPermissionRelation(id);

        employeeMapper.deleteEmpAndRoleRelation(null, id);
    }

    @Transactional(readOnly = true)
    public Role get(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Transactional(readOnly = true)
    public List<Role> listAll() {
        return mapper.selectAll();
    }

    @Transactional(readOnly = true)
    public PageResult<Role> query(QueryObject qo) {
        //查总条数
        int count = mapper.selectForCount(qo);

        //总条数不为0的时候查结果集
        if(count == 0){
            return new PageResult<Role>(qo.getCurrentPage(),qo.getPageSize());
        }
        List<Role> list = mapper.selectForList(qo);
        return new PageResult<Role>(list,qo.getCurrentPage(),qo.getPageSize(),count);
    }


}
